<template>
  <view class="message-container">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <text class="nav-title">消息中心</text>
    </view>

    <!-- 消息筛选栏 -->
    <view class="filter-bar">
      <view class="filter-wrapper">
        <button 
          class="filter-btn" 
          :class="currentFilter === 'all' ? 'filter-btn-active' : ''"
          @click="changeFilter('all')"
        >
          全部消息
        </button>
        <button 
          class="filter-btn" 
          :class="currentFilter === 'unread' ? 'filter-btn-active' : ''"
          @click="changeFilter('unread')"
        >
          未读消息
          <view class="unread-badge" v-if="unreadCount > 0">
            {{ unreadCount > 99 ? '99+' : unreadCount }}
          </view>
        </button>
        <button 
          class="mark-all-read-btn"
          @click="handleMarkAllRead"
          v-if="unreadCount > 0"
        >
          全部已读
        </button>
      </view>
    </view>

    <!-- 消息列表区域：自定义加载动画（无Uni-UI依赖） -->
    <view class="message-list">
      <!-- 1. 自定义加载状态（替换uni-loading-icon） -->
      <view class="custom-loading" v-if="isLoading">
        <view class="loading-spinner"></view> <!-- CSS旋转动画 -->
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 2. 消息列表项 -->
      <view 
        class="message-item" 
        v-for="(msg, index) in messageList" 
        :key="index"
        @click="handleGotoDetail(msg.id)"
        v-else-if="messageList.length > 0"
      >
        <view class="unread-dot" v-if="!msg.isRead"></view>
        <view class="message-content">
          <text class="message-title">{{ msg.title || '无标题通知' }}</text>
          <text class="message-desc">
            {{ msg.content.length > 30 ? msg.content.slice(0, 30) + '...' : msg.content }}
          </text>
          <text class="message-time">{{ formatTime(msg.createTime) }}</text>
        </view>
      </view>

      <!-- 3. 空状态 -->
      <view class="empty-state" v-else>
        <text class="empty-icon">📭</text>
        <text class="empty-text">
          {{ currentFilter === 'unread' ? '暂无未读消息' : '暂无消息记录' }}
        </text>
      </view>
    </view>

    <!-- 底部导航 -->
    <bottom-nav :current-path="currentPagePath"></bottom-nav>
  </view>
</template>

<script>
// 关键修改1：移除uni-loading-icon的导入
import bottomNav from '@/pages/components/bottom-nav/bottom-nav.vue';
// 确保request.js路径正确（根据你的实际路径调整）
import api from '@/api/request.js';

export default {
  components: {
    bottomNav,
    // 关键修改2：移除uni-loading-icon的组件注册
  },
  data() {
    return {
      currentPagePath: '/pages/Employee/message/message',
      currentFilter: 'all',
      messageList: [],
      unreadCount: 0,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        status: undefined
      },
      totalCount: 0,
      isLoading: false, // 加载状态控制（复用原变量）
      isNoMore: false
    };
  },
  onLoad() {
    this.resetPageParams();
    this.getNotificationList();
  },
  onShow() {
    this.getNotificationList();
  },
  onReachBottom() {
    if (!this.isLoading && !this.isNoMore) {
      this.pageParams.pageNo += 1;
      this.getNotificationList();
    }
  },
  methods: {
    resetPageParams() {
      this.pageParams = {
        pageNo: 1,
        pageSize: 10,
        status: this.currentFilter === 'unread' ? 0 : undefined
      };
      this.messageList = [];
      this.isNoMore = false;
    },

    // 核心接口请求逻辑（无修改，仅依赖request.js）
    getNotificationList() {
      if (this.isLoading) return;
      this.isLoading = true;

      const requestData = {
        pageNo: this.pageParams.pageNo,
        pageSize: this.pageParams.pageSize,
        status: this.pageParams.status
      };

      api.postJson(
        '/api/employeeNotification/queryPageList',
        requestData,
        true
      )
      .then((res) => {
        const { records, total, current, pages } = res;
        const formattedList = records.map(item => ({
          id: item.id,
          title: item.title,
          content: item.content,
          createTime: item.createTime,
          isRead: item.status === 1,
          type: item.type
        }));

        this.messageList = this.pageParams.pageNo === 1 
          ? formattedList 
          : [...this.messageList, ...formattedList];
        this.totalCount = total;
        this.isNoMore = current >= pages;
        this.calcUnreadCount();
      })
      .catch((err) => {
        this.handleRequestError(err);
      })
      .finally(() => {
        this.isLoading = false; // 结束加载，隐藏自定义动画
      });
    },

    markAsRead(notificationId) {
      return new Promise((resolve, reject) => {
        api.post(
          '/api/employeeNotification/markAsRead',
          { id: notificationId },
          true
        )
        .then((isSuccess) => {
          if (isSuccess) {
            const targetIndex = this.messageList.findIndex(item => item.id === notificationId);
            if (targetIndex !== -1) {
              this.messageList[targetIndex].isRead = true;
              this.calcUnreadCount();
            }
            resolve(true);
          } else {
            uni.showToast({ title: '标记已读失败', icon: 'none' });
            resolve(false);
          }
        })
        .catch((err) => {
          this.handleRequestError(err);
          reject(err);
        });
      });
    },

    handleMarkAllRead() {
      uni.showModal({
        title: '确认操作',
        content: '是否将所有未读消息标记为已读？',
        success: (modalRes) => {
          if (modalRes.confirm) {
            api.post(
              '/api/employeeNotification/markAllAsRead',
              {},
              true
            )
            .then((isSuccess) => {
              if (isSuccess) {
                uni.showToast({ title: '全部标记已读成功' });
                this.getNotificationList();
              } else {
                uni.showToast({ title: '标记失败', icon: 'none' });
              }
            })
            .catch((err) => {
              this.handleRequestError(err);
            });
          }
        }
      });
    },

    changeFilter(filterType) {
      if (this.currentFilter === filterType) return;
      this.currentFilter = filterType;
      this.resetPageParams();
      this.getNotificationList();
    },

    handleGotoDetail(notificationId) {
      this.markAsRead(notificationId)
        .then((isSuccess) => {
          if (isSuccess) {
            uni.navigateTo({
              url: `/pages/Employee/message/detail?msgId=${notificationId}`
            });
          }
        });
    },

    calcUnreadCount() {
      this.unreadCount = this.messageList.filter(item => !item.isRead).length;
    },

    handleRequestError(err) {
      switch (err.type) {
        case 'business':
          if (err.code === 100002 || err.code === 100004) {
            uni.removeStorageSync('token');
            uni.redirectTo({ url: '/pages/login/login' });
            uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
          } else {
            uni.showToast({ title: err.msg || '操作失败', icon: 'none' });
          }
          break;
        case 'network':
          uni.showToast({ title: '网络异常，请检查网络', icon: 'none' });
          break;
        case 'http':
          uni.showToast({ title: `请求失败(${err.statusCode})`, icon: 'none' });
          break;
        default:
          uni.showToast({ title: '未知错误', icon: 'none' });
      }
      console.error('接口请求错误：', err);
    },

    formatTime(time) {
      if (!time) return '未知时间';
      const date = typeof time === 'string' 
        ? new Date(time.replace(/-/g, '/')) 
        : new Date(time);
      if (isNaN(date.getTime())) return '时间格式错误';

      const padZero = (num) => num.toString().padStart(2, '0');
      const year = date.getFullYear();
      const month = padZero(date.getMonth() + 1);
      const day = padZero(date.getDate());
      const hours = padZero(date.getHours());
      const minutes = padZero(date.getMinutes());

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }
};
</script>

<style scoped>
.message-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-top: 45px;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 45px;
  background-color: #165dff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  z-index: 99;
}
.nav-title {
  font-size: 18px;
  color: #fff;
  font-weight: 500;
}

.filter-bar {
  background-color: #fff;
  padding: 12px 15px;
  border-bottom: 1px solid #e5e6eb;
}
.filter-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}
.filter-btn {
  flex: 1;
  padding: 8px 0;
  background-color: #f5f7fa;
  color: #86909c;
  font-size: 14px;
  border-radius: 8px;
  position: relative;
}
.filter-btn-active {
  background-color: #165dff;
  color: #fff;
}
.unread-badge {
  position: absolute;
  top: -5px;
  right: -8px;
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  font-size: 12px;
  color: #fff;
  background-color: #ff4d4f;
  border-radius: 50%;
  padding: 0 4px;
}
.mark-all-read-btn {
  padding: 8px 12px;
  background-color: #fff;
  color: #165dff;
  font-size: 14px;
  border: 1px solid #165dff;
  border-radius: 8px;
}
.mark-all-read-btn:active {
  background-color: #f0f7ff;
}

.message-list {
  padding: 10px 15px;
}

/* 关键修改3：自定义加载动画样式（替代uni-loading-icon） */
.custom-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}
/* 旋转的加载图标 */
.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(22, 93, 255, 0.2); /* 淡蓝色边框 */
  border-top-color: #165dff; /* 顶部蓝色边框（旋转时显为动画） */
  border-radius: 50%;
  animation: spin 1s linear infinite; /* 无限旋转动画 */
  margin-right: 8px;
}
/* 旋转动画关键帧 */
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.loading-text {
  font-size: 14px;
  color: #86909c;
}

/* 消息项、空状态样式不变 */
.message-item {
  display: flex;
  align-items: flex-start;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: background-color 0.2s;
}
.message-item:active {
  background-color: #f9f9f9;
}
.unread-dot {
  width: 8px;
  height: 8px;
  background-color: #ff4d4f;
  border-radius: 50%;
  margin-top: 7px;
  margin-right: 12px;
}
.message-content {
  flex: 1;
}
.message-title {
  display: block;
  font-size: 16px;
  color: #272e3b;
  font-weight: 500;
  margin-bottom: 5px;
}
.message-desc {
  display: block;
  font-size: 14px;
  color: #4e5969;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.message-time {
  display: block;
  font-size: 12px;
  color: #86909c;
  text-align: right;
}
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
}
.empty-icon {
  font-size: 60px;
  color: #ddd;
  margin-bottom: 20px;
}
.empty-text {
  font-size: 14px;
  color: #86909c;
}
</style>